package com.qiantu.phone.ui.activity;

import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.RoomBean;
import com.qiantu.api.entity.SceneDetailBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.RecommendSceneDeviceBean;
import com.qiantu.phone.bean.RecommendSceneBean;
import com.qiantu.phone.ui.adapter.RecommendSceneActionAdapter;
import com.qiantu.phone.ui.uiutil.LLSceneLinkageUtil;
import com.qiantu.phone.utils.DataHolder;
import com.qiantu.phone.utils.TempDataHolder;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class RecommendSceneDeviceActionActivity extends AppActivity {

    private View bg;
    private TextView tvSceneName;
    private RecyclerView mRecyclerView;
    private View btnOneClickCreate;
    private RecommendSceneBean data;
    private RecommendSceneActionAdapter mRecommendSceneActionAdapter;
    private SceneDetailBean sceneDetailBean;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_recommend_scene_action;
    }

    @Override
    protected void initView() {
        bg = findViewById(R.id.bg);
        tvSceneName = findViewById(R.id.tv_scene_name);
        mRecyclerView = findViewById(R.id.recycler_view);
        btnOneClickCreate = findViewById(R.id.btn_one_click_create);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecommendSceneActionAdapter = new RecommendSceneActionAdapter(this);
        mRecommendSceneActionAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                RecommendSceneDeviceBean recommendSceneDeviceBean = mRecommendSceneActionAdapter.getData().get(position);
                Intent intent = new Intent(getContext(), MultipleSelectDeviceActivity.class);
                intent.putExtra("deviceMainType", recommendSceneDeviceBean.getBaseType());
                startActivityForResult(intent, new OnActivityCallback() {
                    @Override
                    public void onActivityResult(int resultCode, @Nullable Intent data) {
                        if(resultCode == RESULT_OK){
                            List<DeviceBean> selectedDevices = (List<DeviceBean>) DataHolder.getInstance().getData(recommendSceneDeviceBean.getBaseType());
                            recommendSceneDeviceBean.setSelectedDeviceCount(selectedDevices == null ? 0 : selectedDevices.size());
                            mRecommendSceneActionAdapter.notifyItemChanged(position);
                            int allSelectedDeviceCount = 0;
                            for(RecommendSceneDeviceBean recommendSceneDevice : mRecommendSceneActionAdapter.getData()){
                                allSelectedDeviceCount += recommendSceneDevice.getSelectedDeviceCount();
                            }
                            if(allSelectedDeviceCount > 0){
                                btnOneClickCreate.setEnabled(true);
                            }else{
                                btnOneClickCreate.setEnabled(false);
                            }
                        }
                    }
                });
            }
        });
        mRecyclerView.setAdapter(mRecommendSceneActionAdapter);
        setOnClickListener(R.id.btn_one_click_create);
        btnOneClickCreate.setEnabled(false);
    }

    @Override
    protected void initData() {
        data = getParcelable("data");
        tvSceneName.setText(data.getName());
        if(data != null && data.getDevices() != null){
            getDeviceCount = 0;
            for(RecommendSceneDeviceBean recommendSceneDevice : data.getDevices()){
                getAvailableDeviceByMainType(recommendSceneDevice);
            }
            sceneDetailBean = new SceneDetailBean();
            sceneDetailBean.setHouseSerialNo(AppApplication.getInstance().getCurHouseInfo().getHouseSerialNo());
            sceneDetailBean.setRoomSerialNo(RoomBean.ROOM_COMMON_SERIALNO);
            sceneDetailBean.setFavourite(true);
            sceneDetailBean.setSceneType(1);
            sceneDetailBean.setSceneTasks(new ArrayList<>());
            sceneDetailBean.setImage(data.getSceneIcon());
            sceneDetailBean.setName(data.getName());
            TempDataHolder.setEditSceneDetailBean(sceneDetailBean);
        }
    }

    private int getDeviceCount = 0;
    private void getAvailableDeviceByMainType(RecommendSceneDeviceBean recommendSceneDevice){
        Observable.create(new ObservableOnSubscribe<List<DeviceBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<DeviceBean>> emitter) throws Exception {
                List<DeviceBean> devices = LLDeviceDBManager.getInstance(getContext()).getAvailableDeviceByMainType(recommendSceneDevice.getBaseType());
                emitter.onNext(devices);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<DeviceBean>>() {
                    @Override
                    public void accept(List<DeviceBean> devices) throws Exception {
                        getDeviceCount++;
                        recommendSceneDevice.setSelectedDeviceCount(devices == null ? 0 : devices.size());
                        DataHolder.getInstance().setData(recommendSceneDevice.getBaseType(), devices);
                        if(getDeviceCount == data.getDevices().size()){
                            mRecommendSceneActionAdapter.setData(data.getDevices());
                            int allSelectedDeviceCount = 0;
                            for(RecommendSceneDeviceBean recommendSceneDevice : mRecommendSceneActionAdapter.getData()){
                                allSelectedDeviceCount += recommendSceneDevice.getSelectedDeviceCount();
                            }
                            if(allSelectedDeviceCount > 0){
                                btnOneClickCreate.setEnabled(true);
                            }else{
                                btnOneClickCreate.setEnabled(false);
                            }
                            int res = getContext().getResources().getIdentifier(data.getImage(), "mipmap", getContext().getPackageName());
                            if(res != 0){
                                bg.setBackgroundResource(res);
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        ToastUtils.show(R.string.load_area_data_failed);
                    }
                });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.btn_one_click_create:
                for(RecommendSceneDeviceBean recommendSceneDevice : data.getDevices()){
                    List<DeviceBean> selectedDevices = (List<DeviceBean>) DataHolder.getInstance().getData(recommendSceneDevice.getBaseType());
                    for(DeviceBean device : selectedDevices){
                        LLSceneLinkageUtil.addDeviceInstruct(sceneDetailBean, device, recommendSceneDevice.getOpeartion().getStatus(), -1);
                    }
                }
                Intent intent = new Intent(this, EditSceneActivityNew.class);
                intent.putExtra("isRecommendScene", true);
                startActivity(intent);
//                LLHttpManager.sceneCreate(this, sceneDetailBean, new HttpCallback<HttpData<CreateSceneResult>>(this){
//                    @Override
//                    public void onSucceed(HttpData<CreateSceneResult> result) {
//                        super.onSucceed(result);
//                        SceneBean scene = result.getData().getCreateSceneDto();
//                        LLSceneDBManager.getInstance(getContext()).put(scene);
//                        EventBus.getDefault().post(new RefreshSceneEvent());
//                        //添加常用场景，并且当前没有常用场景和设备就要刷新首页楼层或者房间栏
//                        if(sceneDetailBean.getFavourite() != null && sceneDetailBean.getFavourite()){
//                            EventBus.getDefault().post(new UpdateFavouriteEvent(UpdateFavouriteEvent.TYPE_ADD));
//                        }
//                        //如果从触发条件页面进来，完成后关闭触发条件页面
//                        ActivityManager.getInstance().finishActivity(AddConditionActivity.class);
//                        finish();
//                        toast(R.string.create_success);
//                    }
//                });
                break;
        }
    }

    @Override
    public void finish() {
        TempDataHolder.clearEditSceneDetailBean(sceneDetailBean.getSceneType());
        clearSelectedDevices();
        super.finish();
    }

    @Override
    public void onBackPressed() {
        TempDataHolder.clearEditSceneDetailBean(sceneDetailBean.getSceneType());
        clearSelectedDevices();
        super.onBackPressed();
    }

    private void clearSelectedDevices(){
        for(RecommendSceneDeviceBean recommendSceneDevice : data.getDevices()){
            DataHolder.getInstance().clearData(recommendSceneDevice.getBaseType());
        }
    }

    @Override
    protected boolean isStatusBarDarkFont() {
        return false;
    }
}